import React, { useEffect, useCallback } from 'react';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';
import {
  Page, Header, Content, Breadcrumb,
} from '@choerodon/boot';
import { Button } from 'choerodon-ui/pro';
import { Divider } from 'choerodon-ui';
import { getIsOrganization } from '@/utils/common';
import useIssueTypes from '@/hooks/data/useIssueTypes';
import { IIssueType } from '@/common/types';
import openSelectExistStatus from '../components/select-exist-status';
import openCreateStatus from '../components/create-status';
import openSetDefaultStatus from '../components/set-default-status';
import openConfirmLeave from './components/confirm-leave';
import StatusCirculationTable from './components/status-circulation-table';
import { TabComponentProps } from '..';
import { useStatusCirculationContext } from './index';
import { useStateMachineContext } from '../context';
import IssueTypeTab from '../components/issue-type-tab';
import Save from './components/save';

const StatusCirculation: React.FC<TabComponentProps> = ({ tab }) => {
  const { store } = useStatusCirculationContext();
  const { data: issueTypes } = useIssueTypes();
  const {
    selectedType, setSelectedType, issueTypeInitedMap, readOnly, visibleIssueTypeCategory,
  } = useStateMachineContext();
  const isOrganization = getIsOrganization();
  // const selectedTypeRef = useRef<string>(selectedType);
  // selectedTypeRef.current = selectedType;
  const refresh = useCallback(() => {
    if (selectedType && issueTypes?.find((item: IIssueType) => item.id === selectedType) && ((isOrganization && issueTypeInitedMap.get(selectedType)) || !isOrganization)) {
      store.getStatusList(selectedType);
    }
  }, [isOrganization, issueTypeInitedMap, issueTypes, selectedType, store]);
  useEffect(() => {
    refresh();
  }, [refresh]);
  // useEffect(() => () => {
  //   if (store.hasAction) {
  //     openConfirmLeave({
  //       onOk: async () => {
  //         await store.batchUpdateStatusTransform(selectedTypeRef.current);
  //       },
  //     });
  //   }
  // }, []);
  return (
    <Page>
      {
        !readOnly && (
          <>
            <Header>
              <Button
                icon="playlist_add"
                onClick={() => {
                  openSelectExistStatus({
                    statusList: store.statusList,
                    issueTypeId: selectedType,
                    onSubmit: () => {
                      refresh();
                    },
                  });
                }}
              >
                添加已有状态
              </Button>
              <Button
                icon="playlist_add"
                onClick={() => {
                  openCreateStatus({
                    selectedIssueType: [selectedType],
                    onSubmit: () => {
                      refresh();
                    },
                  });
                }}
              >
                创建新的状态
              </Button>
              <Button
                icon="settings-o"
                onClick={() => {
                  openSetDefaultStatus({
                    issueTypeId: selectedType,
                    statusList: toJS(store.statusList),
                    onSubmit: refresh,
                  });
                }}
              >
                设置初始状态
              </Button>
            </Header>
            <Breadcrumb />
          </>
        )
      }

      {
        !isOrganization && (
          <Divider style={{ margin: 0 }} />
        )
      }
      <Content style={{ display: 'flex', flexDirection: 'column', paddingBottom: 0 }}>
        <IssueTypeTab
          selectedType={selectedType}
          setSelectedType={(newType) => {
            if (store.hasAction) {
              openConfirmLeave({
                onOk: async () => {
                  store.clearActions();
                  setSelectedType(newType);
                },
              });
            } else {
              setSelectedType(newType);
            }
          }}
          excludeTypes={isOrganization ? ['feature', 'issue_epic', 'issue_auto_test', 'issue_test'] : []}
          brighter={readOnly}
          visibleIssueTypeCategory={visibleIssueTypeCategory}
        />
        {tab}
        <div style={{ flex: 1, overflow: 'hidden', display: 'flex' }}>
          <StatusCirculationTable />
        </div>
        <Save />
      </Content>
    </Page>
  );
};

export default observer(StatusCirculation);
